<template>
  <el-container style="height: 100%; padding: 10px 10px 0 10px">
    <el-aside width="20%" style="background-color: #fff; margin: 0; padding: 0; max-width: 200px">
      <el-select v-model="currSpecialTypeId" placeholder="请选择专业类别" size="mini" clearable filterable style="width: 100%">
        <el-option v-for="dict in specialTypes" :key="dict.value" :label="dict.label" :value="dict.value" />
      </el-select>
      <el-input v-model="currTypeName" placeholder="请输入阶段名称" size="mini" clearable prefix-icon="el-icon-search" style="margin-bottom: 10px" />
      <div class="aside-list" :class="{ disabled: loading }">
        <div class="item ellipsis" v-for="(item, index) in filteredCheckTypeList" :key="index" :title="item.typeName" :class="{ active: item.typeId === queryParams.typeId }" @click="onCheckType(item)">
          {{ item.typeName }}
        </div>
      </div>
    </el-aside>
    <el-main style="padding: 0 0 0 20px">
      <el-form ref="queryForm" :model="queryParams" size="mini" inline style="white-space: nowrap; overflow-x: auto">
        <el-form-item prop="typeId" class="hide" />
        <el-form-item prop="tableCode">
          <el-input v-model.trim="queryParams.tableCode" placeholder="请输入编码" clearable @keyup.enter.native="handleQuery" style="width: 130px" />
        </el-form-item>
        <el-form-item prop="tableName">
          <el-input v-model.trim="queryParams.tableName" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery" style="width: 130px" />
        </el-form-item>
        <el-form-item prop="specialTypeId">
          <el-select v-model="queryParams.specialTypeId" placeholder="专业类别" clearable filterable style="width: 130px">
            <el-option v-for="dict in specialTypes" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button size="mini" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          <el-button size="mini" :icon="isExpand ? 'el-icon-arrow-down' : 'el-icon-arrow-right'" @click="handleExpandDebounce">全部{{ isExpand ? '折叠' : '展开' }}</el-button>
          <el-button size="mini" type="primary" icon="el-icon-plus" @click="openEditCheckTable()" v-hasPermi="['cq:checkTable:add']" v-if="queryParams.typeId">新增</el-button>
          <el-popover placement="top" trigger="hover" content="请点击选择左侧阶段列表" v-else>
            <el-button slot="reference" size="mini" icon="el-icon-plus" v-hasPermi="['cq:checkTable:add']" style="margin-left: 10px">新增</el-button>
          </el-popover>
        </el-form-item>
      </el-form>

      <el-table class="g-table-tree-expand-align" ref="table" v-loading="loading" :data="list" size="small" row-key="tableId" :default-expand-all="isExpand" height="calc(100vh - 150px)">
        <el-table-column label="工序编码" prop="tableCode" show-overflow-tooltip min-width="150" class-name="expand-column" />
        <el-table-column label="工序名称" prop="tableName" show-overflow-tooltip min-width="200" />
        <el-table-column label="验收对象" prop="unitType" align="center" min-width="80">
          <span slot-scope="{ row }">{{ row.unitType | selectEnumLabel(unitTypeEnum) }}</span>
        </el-table-column>
        <el-table-column label="工程师验收比例（%）" prop="gcsPercent" align="center" min-width="120" />
        <el-table-column label="监理验收比例（%）" prop="jlPercent" align="center" min-width="120" />
        <el-table-column label="项目总验收比例（%）" prop="xmzPercent" align="center" min-width="120" />
        <el-table-column label="项目经理验收比例（%）" prop="xmjlPercent" align="center" min-width="130" />
        <el-table-column label="专业类别" align="center" min-width="70">
          <dict-tag slot-scope="{ row }" :options="specialTypes" :value="row.specialTypeId" />
        </el-table-column>
        <el-table-column label="报验是否上传附件" align="center" min-width="130">
          <el-tag slot-scope="{ row }" size="small" :type="row.isReqAttch ? 'primary' : 'info'">{{ row.isReqAttch ? '是' : '否' }}</el-tag>
        </el-table-column>
        <el-table-column label="是否启用" align="center" min-width="80">
          <el-tag slot-scope="{ row }" size="small" :type="row.isEnable ? 'primary' : 'info'">{{ row.isEnable ? '是' : '否' }}</el-tag>
        </el-table-column>
        <el-table-column label="排序" prop="seq" align="center" width="80" />
        <el-table-column label="操作" fixed="right" align="center" width="180">
          <div slot-scope="{ row }" style="text-align: left">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="$refs.EditCheckTable.open(row, { checkTypeList, checkTableList, unitTypeEnum })" v-hasPermi="['cq:checkTable:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" :loading="row.removeLoading" @click="handleDelete(row)" v-hasPermi="['cq:checkTable:remove']">删除</el-button>
            <el-button size="mini" type="text" icon="el-icon-plus" @click="openEditCheckTable(row.tableId)" v-hasPermi="['cq:checkTable:add']">新增</el-button>
          </div>
        </el-table-column>
      </el-table>
    </el-main>
    <EditCheckTable ref="EditCheckTable" v-model="showEditCheckTable" @ok="getList" />
  </el-container>
</template>
<script>
// 工程质量-工序页面
import { debounce, flatList2tree, isLikeOrEqual } from '@/utils'
import { getSpecialTypes } from '@/utils/dict/custom'
import { getEnum } from '@/api/common'
import { listCheckType, listCheckTable, delCheckTable } from '@/api/qualityManage/cq'
import EditCheckTable from './components/EditCheckTable'
export default {
  // eslint-disable-next-line
  name: '/cq/checkTable',
  components: { EditCheckTable },
  data() {
    return {
      isExpand: true,
      loading: false,
      list: [], // 工序树形数据
      queryParams: {
        typeId: '',
        tableCode: '',
        tableName: '',
        specialTypeId: ''
      },
      showEditCheckTable: false,
      checkTypeList: [], // 阶段
      checkTableList: [], // 工序原数据
      unitTypeEnum: [], // 验收对象
      specialTypes: [], // 专业类别
      currSpecialTypeId: '', // 当前选中专业类别ID
      currTypeName: ''
    }
  },
  computed: {
    filteredCheckTypeList() {
      // 本地过滤
      const specialTypeId = this.currSpecialTypeId
      const typeName = this.currTypeName
      const opts = { like: { typeName }, eq: { specialTypeId } }
      return this.checkTypeList.filter(i => isLikeOrEqual(i, opts))
    }
  },
  created() {
    this.handleExpandDebounce = debounce(this.handleExpand)
    this.getCheckTypeList()
    getEnum('unitType').then(res => (this.unitTypeEnum = res.data.unitType))
    getSpecialTypes().then(res => (this.specialTypes = res))
  },
  methods: {
    // 递归切换展开状态
    setChildren(children, expanded) {
      children.map(row => {
        this.$refs.table.toggleRowExpansion(row, expanded)
        if (row.children) this.setChildren(row.children, expanded)
      })
    },
    // 展开/折叠
    handleExpand() {
      this.isExpand = !this.isExpand
      this.setChildren(this.list, this.isExpand)
    },
    async getCheckTypeList() {
      const res = await listCheckType().catch(() => false)
      if (res === false) return

      const data = res.data || []
      this.checkTypeList = data
      if (!data.length) return
      this.queryParams.typeId = data[0].typeId
      this.getList()
    },
    async getList() {
      this.loading = true
      const res = await listCheckTable(this.queryParams).catch(() => false)
      this.loading = false
      if (res === false) return

      let data = res.data || []
      this.checkTableList = JSON.parse(JSON.stringify(data))
      data.map(i => {
        i.removeLoading = false
      })
      data = flatList2tree(data, { id: 'tableId' })
      this.list = data
      this.isExpand = true
    },
    handleQuery() {
      this.getList()
    },
    resetQuery() {
      this.currSpecialTypeId = ''
      this.currTypeName = ''
      this.resetForm('queryForm')
      this.handleQuery()
    },
    onCheckType(item) {
      this.queryParams.typeId = item.typeId
      this.handleQuery()
    },
    openEditCheckTable(parentId) {
      const { checkTypeList, checkTableList, unitTypeEnum } = this
      this.$refs.EditCheckTable.open({ typeId: this.queryParams.typeId, parentId }, { checkTypeList, checkTableList, unitTypeEnum })
    },
    async handleDelete(item) {
      if (item.removeLoading) return
      const res1 = await this.$confirm('确认删除工序名称为"' + item.tableName + '"的数据项?', '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      item.removeLoading = true
      const res = await delCheckTable(item.tableId).catch(() => false)
      item.removeLoading = false
      if (res === false) return

      this.msgSuccess('删除成功')
      this.getList()
    }
  }
}
</script>
<style lang="scss" scoped>
.aside-list {
  height: calc(100% - 90px);
  overflow: auto;
  font-size: 12px;
  color: #606266;
  &.disabled {
    pointer-events: none;
  }
  .item {
    padding: 0 10px;
    cursor: pointer;
    &:hover {
      background-color: #f5f7fa;
    }
    &.active {
      background-color: #409eff;
      color: white;
    }
  }
}
</style>
